package com.ampaiva.organizescreen.controller;

import java.security.InvalidParameterException;
import java.util.ArrayList;

public class MoveList {
	private final ArrayList<IMovieListElement> list;

	public interface IMovieListElement {
		public void setPosition(int position);
	}

	public MoveList(int capacity) {
		list = new ArrayList<IMovieListElement>(capacity);
	}

	public void append(IMovieListElement element) {
		if (list.indexOf(element) >= 0)
			throw new InvalidParameterException("Element is already part of list at position " + list.indexOf(element));
		list.add(element);
		element.setPosition(list.indexOf(element));
	}

	public void put(int index, IMovieListElement entering) {
		if (index < 0 || index > list.size())
			throw new InvalidParameterException("Invalid index " + index);

		int actualPosition = list.indexOf(entering);
		if (actualPosition == index)
			return;
		if (index > list.size()) {
			append(entering);
			return;
		}
		IMovieListElement current = list.get(index);
		if (actualPosition >= 0) {
			list.set(actualPosition, current);
			current.setPosition(actualPosition);
		} else {
			list.set(index, null);
			append(current);
		}

		list.set(index, entering);
		entering.setPosition(list.indexOf(entering));
	}
}
